package comtgl.demo.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonParser;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.calendar.v4.model.*;
import com.lark.oapi.service.contact.v3.model.*;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

public class FeiShuAPIUtil {
//    static String appId = "cli_a8a6f8146ab6900b";
//    static String appSecret = "1bn22SX844MToP9GA1qbKhObDuKVlJIy";
    static String appId = "cli_a7761ab61c79900e";
    static String appSecret = "BseeMx32Fzx0BXfK33YbOgjFSFVPrdSb";
    //外协
//    static String appId = "cli_a8ab7cb264f7d00d";
//    static String appSecret = "OSxdA7vC3uL5Ps8CABVnFbihLioCQdgl";

    public static void main(String[] args) throws Exception {
//        GetDepartmentResp dept = getDept();
        getUser11();
//        ParentDepartmentResp pareDept = getPareDept("od-a9a85a22f0b262652b9c7a6bfb3a0161");
////        List<Department> items = pareDept.getData().getItems();
////        Department[] items = pareDept.getData().getItems();
//        Department[] departments = pareDept.getData().getItems();
//        List<Department> departmentList = new ArrayList<>();
////        departmentList.add(dept.getData().getDepartment());
//        String lastODeptId = "";
//        for (Department department : departments) {
//            departmentList.add(department);
//            lastODeptId = department.getOpenDepartmentId();
//        }
//
//        System.out.println(pareDept);
//        Boolean hasMore = pareDept.getData().getHasMore();
//        while(hasMore) {
//            ParentDepartmentResp pareDept1 = getPareDept(lastODeptId);
//            departmentList.addAll(new HashSet<>(Arrays.asList(pareDept1.getData().getItems())));
//            for (Department department : pareDept1.getData().getItems()) {
//                departmentList.add(department);
//                lastODeptId = department.getOpenDepartmentId();
//            }
//            hasMore = pareDept1.getData().getHasMore();
//        }
//        StringBuffer sbuf = new StringBuffer();
//        for (int i= departmentList.size()-1;i>=0;i--) {
//            sbuf.append(departmentList.get(i).getName()).append("/");
//        }
//        System.out.println(sbuf.toString());
//        getToken();
//        getReleationOrg();
//        System.out.println(getReleationUser("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy","14acc306496fd740","tongguoliang.ex"));
//        calendar();
//        getOpenId();
//        createEvent();
//        scheduleList();
//        deleteMember();
//        addEventAttendee();
//        eventAttendee();
//        updateEvent();
    }

    public static void getUser11() throws Exception {
        // 构建client
        Client client = Client.newBuilder(appId, appSecret).build();

        // 创建请求对象
        GetUserReq req = GetUserReq.newBuilder()
//                .userId("liuzhicheng.ex")
                .userId("wangduo3")
                .userIdType("user_id")
                .departmentIdType("open_department_id")
                .build();

        // 发起请求
        GetUserResp resp = client.contact().v3().user().get(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public static ParentDepartmentResp getPareDept(String dept) throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        ParentDepartmentReq req = ParentDepartmentReq.newBuilder()
                .userIdType("user_id")
                .departmentIdType("open_department_id")
                .departmentId(dept)
                .pageSize(20)
                .build();

        // 发起请求
        return client.contact().v3().department().parent(req);


    }

    public static void getToken() throws Exception {

        //1.获取 tenant_access_token
        String requestBody = String.format("""
                    {
                        "app_id": "%s",
                        "app_secret": "%s"
                    }
                """, appId, appSecret);
        String url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
        String tenant_access_token_res = getPostResponseInfo(url, requestBody, null);
        JSONObject jsonObject = JSONObject.parseObject(tenant_access_token_res);
        String token = jsonObject.getString("tenant_access_token");
        System.out.println("tenant_access_token:" + token);
    }

    public static void updateEvent() throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        PatchCalendarEventReq req = PatchCalendarEventReq.newBuilder()
                .calendarId("feishu.cn_FIzXswRgnuF4f7LAttEkJh@group.calendar.feishu.cn")
                .eventId("6bbeceda-8eaf-4606-a4b7-d26243bab839_0")
                .userIdType("user_id")
                .calendarEvent(CalendarEvent.newBuilder()
//                        .summary("测试日程0604-001")

                        .attendeeAbility("can_modify_event")
                        .build())
                .build();

        // 发起请求
        PatchCalendarEventResp resp = client.calendar().v4().calendarEvent().patch(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public static void addEventAttendee() throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        CreateCalendarEventAttendeeReq req = CreateCalendarEventAttendeeReq.newBuilder()
                .calendarId("feishu.cn_FIzXswRgnuF4f7LAttEkJh@group.calendar.feishu.cn")
                .eventId("6bbeceda-8eaf-4606-a4b7-d26243bab839_0")
//                .calendarId("feishu.cn_Ktl6alcf2zSUyA9pAmaVSe@group.calendar.feishu.cn")
//                .eventId("655dba85-dd85-44c9-95b6-02886ac62ab9_0")
                .userIdType("user_id")
                .createCalendarEventAttendeeReqBody(CreateCalendarEventAttendeeReqBody.newBuilder()
                        .attendees(new CalendarEventAttendee[]{
                                CalendarEventAttendee.newBuilder()
                                        .type("user")
                                        .isOptional(true)
//                                        .userId("ou_653a368d0e69ac4d5b6def90d0690a6c")
                                        .userId("liuyang80")
                                        .approvalReason("申请原因")
                                        .build()
                        })
                        .needNotification(true)
                        .build())
                .build();

        // 发起请求
        CreateCalendarEventAttendeeResp resp = client.calendar().v4().calendarEventAttendee().create(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public static void eventAttendee() throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        ListCalendarEventAttendeeReq req = ListCalendarEventAttendeeReq.newBuilder()
                .calendarId("feishu.cn_FIzXswRgnuF4f7LAttEkJh@group.calendar.feishu.cn")
                .eventId("6a4c88ca-fb66-493c-b15c-42b7b4ac171b_0")
//                .calendarId("feishu.cn_Ktl6alcf2zSUyA9pAmaVSe@group.calendar.feishu.cn")
//                .eventId("655dba85-dd85-44c9-95b6-02886ac62ab9_0")
                .userIdType("open_id")
                .pageSize(20)
                .build();

        // 发起请求
        ListCalendarEventAttendeeResp resp = client.calendar().v4().calendarEventAttendee().list(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public static void scheduleList() throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        ListCalendarEventReq req = ListCalendarEventReq.newBuilder()
                .calendarId("feishu.cn_FIzXswRgnuF4f7LAttEkJh@group.calendar.feishu.cn")
//                .calendarId("feishu.cn_bJLHMzlwh3ACzP9KQV3PTb@group.calendar.feishu.cn")
//                .calendarId("feishu.cn_Ktl6alcf2zSUyA9pAmaVSe@group.calendar.feishu.cn")
                .pageSize(500)
                .build();

        // 发起请求
        ListCalendarEventResp resp = client.calendar().v4().calendarEvent().list(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public static String getReleationUser(String appId, String appSecret, String tenantId, String userId) throws IOException, InterruptedException {
        //1.获取 tenant_access_token
        String requestBody = String.format("""
                    {
                        "app_id": "%s",
                        "app_secret": "%s"
                    }
                """, appId, appSecret);
        String url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
        String tenant_access_token_res = getPostResponseInfo(url, requestBody, null);
        JSONObject jsonObject = JSONObject.parseObject(tenant_access_token_res);
        String token = jsonObject.getString("tenant_access_token");
        // 创建 HttpClient 实例
        HttpClient client = HttpClient.newBuilder().build();

        // 构建请求 5 次/秒
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://open.feishu.cn/open-apis/trust_party/v1/collaboration_tenants/" + tenantId + "/collaboration_users/" + userId + "?target_user_id_type=user_id"))
                .header("Authorization", "Bearer " + token)
                .GET()
                .build();

        try {
            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            JSONObject targetUser = JSONObject.parseObject(response.body());
            if (targetUser.getInteger("code") == 0) {
                if (targetUser.getJSONObject("data") != null) {
                    if (targetUser.getJSONObject("data").getJSONObject("target_user") != null) {
                        return targetUser.getJSONObject("data").getJSONObject("target_user").getString("open_id");
                    }
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void getReleationOrg() throws Exception {
        // 构建client
        // 创建 HttpClient 实例
        HttpClient client = HttpClient.newBuilder().build();

        // 构建请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://open.feishu.cn/open-apis/trust_party/v1/collaboration_tenants?page_size=10"))
                .header("Authorization", "Bearer t-g10477fkCYM2H2PINSLXQIQFVZB7WRUQJGKEFAKR")
                .GET()
                .build();

        try {
            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // 打印响应头
            System.out.println("响应状态码: " + response.statusCode());
            response.headers().map().forEach((name, values) ->
                    System.out.println(name + ": " + String.join(", ", values))
            );

            // 打印响应体
            System.out.println("\n响应体:");
            System.out.println(response.body());

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void getUser() throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        GetUserReq req = GetUserReq.newBuilder()
                .userId("tongguoliang.ex")
                .userIdType("user_id")
                .departmentIdType("department_id")
                .build();

        // 发起请求
        GetUserResp resp = client.contact().v3().user().get(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public static void getOpenId() throws Exception {
        // 构建client  内部应用
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        BatchGetIdUserReq req = BatchGetIdUserReq.newBuilder()
                .userIdType("open_id")
                .batchGetIdUserReqBody(BatchGetIdUserReqBody.newBuilder()
                        .emails(new String[]{
                                "tongguoliang.ex@hx-partners.com",
                                "fanke.ex@hx-partners.com",
                                "liuyang80@hisense.com"
                        })
                        .includeResigned(true)
                        .build())
                .build();

        // 发起请求
        BatchGetIdUserResp resp = client.contact().v3().user().batchGetId(req);
        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public static void calendar() throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        ListCalendarReq req = ListCalendarReq.newBuilder()
                .pageSize(500)
                .build();

        // 发起请求
        ListCalendarResp resp = client.calendar().v4().calendar().list(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public static void deleteMember() throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        BatchDeleteCalendarEventAttendeeReq req = BatchDeleteCalendarEventAttendeeReq.newBuilder()
                .calendarId("feishu.cn_FIzXswRgnuF4f7LAttEkJh@group.calendar.feishu.cn")
                .eventId("6a4c88ca-fb66-493c-b15c-42b7b4ac171b_0")
                .userIdType("user_id")
                .batchDeleteCalendarEventAttendeeReqBody(BatchDeleteCalendarEventAttendeeReqBody.newBuilder()
                        .deleteIds(new CalendarEventAttendeeId[]{
                                CalendarEventAttendeeId.newBuilder()
                                        .type("user")
                                        .userId("haobin.ex")
                                        .build()
                        })
                        .needNotification(false)
                        .instanceStartTimeAdmin("1647320400")
                        .isEnableAdmin(false)
                        .build())
                .build();

        // 发起请求
        BatchDeleteCalendarEventAttendeeResp resp = client.calendar().v4().calendarEventAttendee().batchDelete(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    private static String getPostResponseInfo(String url, String requestBody, String token) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json; charset=utf-8")
                .header("Authorization", "Bearer " + token)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
        // 发送请求
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }

    public static GetDepartmentResp getDept() throws Exception {
        // 构建client
        Client client = Client.newBuilder(appId, appSecret).build();

        // 创建请求对象
        GetDepartmentReq req = GetDepartmentReq.newBuilder()
                .departmentId("od-74c5338330f81cfacee5ab02000d3296")
                .userIdType("user_id")
                .departmentIdType("open_department_id")
                .build();

        // 发起请求
        return client.contact().v3().department().get(req);

    }

    public static void createEvent() throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a8a6f8146ab6900b", "1bn22SX844MToP9GA1qbKhObDuKVlJIy").build();

        // 创建请求对象
        CreateCalendarEventReq req = CreateCalendarEventReq.newBuilder()
                .calendarId("feishu.cn_FIzXswRgnuF4f7LAttEkJh@group.calendar.feishu.cn")
                .userIdType("open_id")
                .calendarEvent(CalendarEvent.newBuilder()
                        .summary("全天测试日程 xx 请无视")
                        .needNotification(false)
                        .startTime(TimeInfo.newBuilder()
                                .date("2025-07-08")
                                .timezone("Asia/Shanghai")
                                .build())
                        .endTime(TimeInfo.newBuilder()
                                .date("2025-07-08")
                                .timezone("Asia/Shanghai")
                                .build())
                        .build())
                .build();

        // 发起请求
        CreateCalendarEventResp resp = client.calendar().v4().calendarEvent().create(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }


}
